<route lang="json">
{
    "name": "adminManage",
    "meta": {
        "title": "控制台-管理员管理",
        "requiresAuth": true
    }
}
</route>

<script setup lang="ts">
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import { addAdmin, deleteAdmin, getAdminList, updateAdmin } from '~/api/admin'
import { getDepartmentList } from '~/api/department'
import { getMenuList } from '~/api/menu'
import { getRoleList } from '~/api/role'

// 定义管理员接口类型
interface Admin {
  adminid: string
  adminname: string
  role: string
  permissions?: (string | number)[]
  departmentId?: string | number
  departmentName?: string
  createTime?: string
  lastLoginTime?: string
  [key: string]: any
}

// 管理员列表数据
const adminList = ref<Admin[]>([])
const loading = ref(false)

// 表格分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
})

// 获取管理员列表
async function fetchAdminList() {
  loading.value = true
  try {
    const res = await getAdminList()
    console.warn('API返回的原始数据:', res)

    // 正确处理API返回的数据结构
    if (res && typeof res === 'object') {
      // 如果返回的是标准格式 {code, message, data}
      if (res.code === '200' && Array.isArray(res.data)) {
        adminList.value = res.data
        pagination.total = adminList.value.length
        console.warn('成功获取管理员列表数据，共', adminList.value.length, '条记录')
      }
      // 如果直接返回了数组
      else if (Array.isArray(res)) {
        adminList.value = res
        pagination.total = res.length
        console.warn('成功获取管理员列表数据，共', adminList.value.length, '条记录')
      }
      // 如果返回的是 {data: [...]} 格式
      else if (res.data && Array.isArray(res.data)) {
        adminList.value = res.data
        pagination.total = res.data.length
        console.warn('成功获取管理员列表数据，共', adminList.value.length, '条记录')
      }
      else {
        adminList.value = []
        pagination.total = 0
        console.warn('API返回的数据格式不符合预期:', res)
      }
    }
    else {
      adminList.value = []
      pagination.total = 0
      console.warn('API返回的数据格式不符合预期:', res)
    }

    loading.value = false
  }
  catch (error) {
    console.error('获取管理员列表失败:', error)
    ElMessage.error('获取管理员列表失败')
    loading.value = false
  }
}

// 表单相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加管理员')
const formRef = ref()
// 定义表单数据类型，与API接口匹配
interface FormDataType {
  adminid: string
  adminname: string
  password: string
  role: string
  checkedKeys: string[] | number[]
  departmentId: string | number
  departmentName: string
}

const formData = reactive<FormDataType>({
  adminid: '',
  adminname: '',
  password: '',
  role: 'admin', // 默认角色
  checkedKeys: [],
  departmentId: '',
  departmentName: '',
})
const formRules = {
  adminname: [
    { required: true, message: '请输入管理员用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' },
  ],
  departmentName: [
    { required: false, message: '请选择部门', trigger: 'change' },
  ],
}

// 角色选项
const roleOptions = ref<{ label: string, value: string }[]>([])

// 部门选项
const departmentOptions = ref<{ label: string, value: string, id: string | number }[]>([])

// 权限选项（菜单）
const permissionOptions = ref<any[]>([])

// 获取角色列表
async function fetchRoleList() {
  try {
    const res = await getRoleList()
    if (res && Array.isArray(res)) {
      roleOptions.value = res.map((role: { roleName: string, roleKey?: string, _id: string }) => ({
        label: role.roleName,
        value: role.roleKey || role._id,
      }))
    }
    else if (res && typeof res === 'object' && Array.isArray(res.data)) {
      roleOptions.value = res.data.map((role: { roleName: string, roleKey?: string, _id: string }) => ({
        label: role.roleName,
        value: role.roleKey || role._id,
      }))
    }
  }
  catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 获取部门列表
async function fetchDepartmentList() {
  try {
    const res = await getDepartmentList(1, 100) // 获取足够多的部门数据
    if (res || res.data) {
      // 递归函数，用于平铺部门树
      function flattenDepartments(departments: any[], result: any[] = []) {
        departments.forEach((dept) => {
          result.push({
            label: dept.name,
            value: dept._id,
            id: dept._id,
          })

          if (dept.children && dept.children.length > 0) {
            flattenDepartments(dept.children, result)
          }
        })
        return result
      }

      departmentOptions.value = flattenDepartments(res || res.data)
    }
  }
  catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
  }
}

// 获取菜单列表（权限选项）
async function fetchMenuList() {
  try {
    const res = await getMenuList()
    if (res && res.menuTree) {
      // 将菜单树转换为权限树结构
      function convertMenuToPermissions(menuItems: any[]): Array<{
        id: string
        label: string
        children?: Array<{
          id: string
          label: string
          children?: any[]
        }>
      }> {
        return menuItems.map((menu) => {
          const item: {
            id: string
            label: string
            children?: any[]
          } = {
            id: menu._id,
            label: menu.menuName,
            children: menu.children && menu.children.length > 0
              ? convertMenuToPermissions(menu.children)
              : undefined,
          }
          return item
        })
      }

      permissionOptions.value = convertMenuToPermissions(res.menuTree)
    }
  }
  catch (error) {
    console.error('获取菜单列表失败:', error)
    ElMessage.error('获取菜单列表失败')
  }
}

// 重置表单
function resetForm() {
  formData.adminid = ''
  formData.adminname = ''
  formData.password = ''
  formData.role = 'admin'
  formData.checkedKeys = []
  formData.departmentId = ''
  formData.departmentName = ''
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 打开添加对话框
function openAddDialog() {
  dialogTitle.value = '添加管理员'
  resetForm()
  dialogVisible.value = true
}

// 打开编辑对话框
function openEditDialog(row: Admin) {
  dialogTitle.value = '编辑管理员'
  resetForm()

  // 填充表单数据
  formData.adminid = row.adminid
  formData.adminname = row.adminname
  formData.role = row.role || 'admin'

  // 确保权限数据类型正确
  if (row.permissions) {
    // 根据类型分别处理
    const isAllNumbers = row.permissions.every(item => typeof item === 'number')
    const isAllStrings = row.permissions.every(item => typeof item === 'string')

    if (isAllNumbers) {
      formData.checkedKeys = row.permissions as number[]
    }
    else if (isAllStrings) {
      formData.checkedKeys = row.permissions as string[]
    }
    else {
      // 如果混合类型，转换为字符串数组
      formData.checkedKeys = row.permissions.map(item => String(item)) as string[]
    }
  }
  else {
    formData.checkedKeys = []
  }

  formData.departmentId = row.departmentId || ''
  formData.departmentName = row.departmentName || ''

  // 如果有部门ID但没有部门名称，尝试从部门选项中找到对应的部门名称
  if (row.departmentId && !row.departmentName) {
    const department = departmentOptions.value.find(item => item.id === row.departmentId)
    if (department) {
      formData.departmentName = department.label
    }
  }

  dialogVisible.value = true
}

// 处理部门选择
function handleDepartmentChange(value: string) {
  const selected = departmentOptions.value.find(item => item.id.toString() === value)
  if (selected) {
    formData.departmentId = selected.id
    formData.departmentName = selected.label
  }
}

// 提交表单
async function submitForm() {
  if (!formRef.value)
    return

  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        if (formData.adminid) {
          // 编辑管理员
          const updateData: {
            adminname: string
            password?: string
            roleKeys?: string[] | number[]
            departmentName?: string
          } = {
            adminname: formData.adminname,
          }

          // 只有当密码不为空时才更新密码
          if (formData.password) {
            updateData.password = formData.password
          }

          // 确保 checkedKeys 类型正确
          if (formData.checkedKeys && formData.checkedKeys.length > 0) {
            const isAllNumbers = formData.checkedKeys.every(item => typeof item === 'number')
            updateData.roleKeys = isAllNumbers
              ? formData.checkedKeys as number[]
              : formData.checkedKeys.map(item => String(item))
          }

          // 添加部门名称
          if (formData.departmentName) {
            updateData.departmentName = formData.departmentName
          }

          await updateAdmin(formData.adminid, updateData)
          ElMessage.success('管理员信息更新成功')
        }
        else {
          // 添加管理员
          // 确保 checkedKeys 类型正确
          const isAllNumbers = formData.checkedKeys.every(item => typeof item === 'number')

          let checkedKeysForApi: string[] | number[]

          if (isAllNumbers) {
            checkedKeysForApi = formData.checkedKeys as number[]
          }
          else {
            // 默认转为字符串数组
            checkedKeysForApi = formData.checkedKeys.map(item => String(item))
          }

          await addAdmin({
            adminname: formData.adminname,
            password: formData.password,
            role: formData.role,
            checkedKeys: checkedKeysForApi,
            departmentId: formData.departmentId,
            departmentName: formData.departmentName,
          })
          ElMessage.success('管理员添加成功')
        }
        dialogVisible.value = false
        fetchAdminList()
      }
      catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败，请重试')
      }
    }
  })
}

// 删除管理员
function handleDelete(row: Admin) {
  ElMessageBox.confirm(
    `确定要删除管理员 ${row.adminname} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(async () => {
    try {
      await deleteAdmin(row.adminid)
      ElMessage.success('删除成功')
      fetchAdminList()
    }
    catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 处理分页变化
function handleCurrentChange(val: number) {
  pagination.currentPage = val
}

function handleSizeChange(val: number) {
  pagination.pageSize = val
  pagination.currentPage = 1
}

// 计算当前页的数据
const currentPageData = computed(() => {
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return adminList.value.slice(start, end)
})

// 页面加载时获取所有必要数据
onMounted(async () => {
  // 并行获取所有数据以提高加载速度
  await Promise.all([
    fetchAdminList(),
    fetchRoleList(),
    fetchDepartmentList(),
    fetchMenuList(),
  ])
})
</script>

<template>
  <div class="admin-manage-container">
    <div class="admin-header">
      <h2 class="admin-title">
        管理员管理
      </h2>
      <el-button type="primary" @click="openAddDialog">
        <el-icon><Plus /></el-icon>添加管理员
      </el-button>
    </div>

    <!-- 管理员列表 -->
    <el-card shadow="hover" class="admin-card">
      <el-table
        v-loading="loading"
        :data="currentPageData"
        stripe
        border
        style="width: 100%"
      >
        <!-- 序号列 -->
        <el-table-column type="index" label="序号" width="60" />

        <!-- ID列，缩短宽度并保留溢出提示 -->
        <el-table-column prop="adminid" label="ID" min-width="140" show-overflow-tooltip />

        <!-- 用户名列 -->
        <el-table-column prop="adminname" label="用户名" min-width="120" />

        <!-- 角色列 -->
        <el-table-column label="角色" width="140">
          <template #default="scope">
            <el-tag type="primary">
              {{ scope.row.role || '普通管理员' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 部门列 -->
        <el-table-column label="部门" width="140">
          <template #default="scope">
            {{ scope.row.departmentName || '-' }}
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" width="160" fixed="right" align="center">
          <template #default="scope">
            <el-button size="small" @click="openEditDialog(scope.row)">
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              :disabled="scope.row.role === 'admin'"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑管理员对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="用户名" prop="adminname">
          <el-input v-model="formData.adminname" placeholder="请输入管理员用户名" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="角色" prop="role">
          <el-select v-model="formData.role" placeholder="请选择角色" style="width: 100%">
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="部门" prop="departmentName">
          <el-select
            v-model="formData.departmentName"
            placeholder="请选择部门"
            style="width: 100%"
            @change="handleDepartmentChange"
          >
            <el-option
              v-for="item in departmentOptions"
              :key="item.id.toString()"
              :label="item.label"
              :value="item.id.toString()"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="权限配置">
          <el-tree
            v-model:checked-keys="formData.checkedKeys"
            :data="permissionOptions"
            show-checkbox
            node-key="id"
            :props="{ children: 'children', label: 'label' }"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="submitForm">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.admin-manage-container {
  padding: 20px;

  .admin-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .admin-title {
      font-size: 20px;
      font-weight: 600;
      margin: 0;
    }
  }

  .admin-card {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
